package com.hqq.controller;

import com.hqq.entity.Student;
import com.hqq.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import java.io.IOException;

public class RegStudentServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {


        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");


        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String age = request.getParameter("age");

        //创建spring容器对象
       // ApplicationContext ctx = new ClassPathXmlApplicationContext("WEB-INF/applicationContext.xml");

        /**
         * 使用监听器
         */
//        WebApplicationContext ctx = null;
//        String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
//        Object attr = getServletContext().getAttribute(key);
//        if (attr != null){
//            ctx = (WebApplicationContext)attr;
//        }

        /**
         * 使用工具类直接生成
         */
        WebApplicationContext ctx = null;
        ServletContext sc = getServletContext();
        ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
        System.out.println("容器对象的信息："+
                ctx);
        //获取service对象
        StudentService studentService = (StudentService)ctx.getBean("studentService");


        Student student = new Student(Integer.parseInt(id),name,email,Integer.parseInt(age));

        studentService.addStudent(student);

        //返还页面
        request.getRequestDispatcher("/result.jsp").forward(request,response);

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

    }
}
